﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// <summary>
///Des 的摘要说明
/// </summary>
public class Des
{
	public Des()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    private string _DESKey = "abcd1234";
    public string DESKey
    {
        set
        {
            _DESKey = value;
        }
    }
    public string DESEncrypt(string toEncrypt)
    {
        //定义DES加密服务提供类
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        //加密字符串转换为byte数组
        byte[] inputByte = System.Text.ASCIIEncoding.UTF8.GetBytes(toEncrypt);
        //加密密匙转化为byte数组
        byte[] key = Encoding.ASCII.GetBytes(_DESKey); //DES密钥(必须8字节)
        des.Key = key;
        des.IV = key;
        //创建其支持存储区为内存的流
        MemoryStream ms = new MemoryStream();
        //定义将数据流链接到加密转换的流
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(inputByte, 0, inputByte.Length);
        cs.FlushFinalBlock();
        StringBuilder ret = new StringBuilder();
        foreach (byte b in ms.ToArray())
        {
            //向可变字符串追加转换成十六进制数字符串的加密后byte数组。
            ret.AppendFormat("{0:X2}", b);
        }
        return ret.ToString();

    }
    public string DESDecrypt(string toDecrypt)
    {
        //定义DES加密解密服务提供类
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        //加密密匙转化为byte数组
        byte[] key = Encoding.ASCII.GetBytes(_DESKey);
        des.Key = key;
        des.IV = key;
        //将被解密的字符串每两个字符以十六进制解析为byte类型，组成byte数组
        int length = (toDecrypt.Length / 2);
        byte[] inputByte = new byte[length];
        for (int index = 0; index < length; index++)
        {
            string substring = toDecrypt.Substring(index * 2, 2);
            inputByte[index] = Convert.ToByte(substring, 16);
        }
        //创建其支持存储区为内存的流
        MemoryStream ms = new MemoryStream();
        //定义将数据流链接到加密转换的流
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(inputByte, 0, inputByte.Length);
        cs.FlushFinalBlock();

        return ASCIIEncoding.UTF8.GetString((ms.ToArray()));
    }
}
